package cn.itsource.hrm.controller;

import cn.itsource.hrm.client.RedisClient;
import cn.itsource.hrm.controller.vo.RegisterVo;
import cn.itsource.hrm.service.ISsoService;
import cn.itsource.util.AjaxResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author chenyuqi
 * @version v1.0.0
 * @date 2020/6/2
 */
@RestController
public class RegisterController {
    @Autowired
    private RedisClient redisClient;

    @Autowired
    private ISsoService ssoService;

    /**
     * 注册
     * @param vo
     * @return
     */
    @PostMapping("/register")
    public AjaxResult register(@RequestBody RegisterVo vo){


        if(StringUtils.isEmpty(vo.getPhoneNum())){
            return AjaxResult.me().setSuccess(false).setMessage("手机号码不能为空!");
        }
        if(StringUtils.isEmpty(vo.getPassword())){
            return AjaxResult.me().setSuccess(false).setMessage("密码不能为空!");
        }
        if(StringUtils.isEmpty(vo.getImageCode())){
            return AjaxResult.me().setSuccess(false).setMessage("图形验证码不能为空!");
        }
        if(StringUtils.isEmpty(vo.getSmsCode())){
            return AjaxResult.me().setSuccess(false).setMessage("短信不能为空!");
        }
        if(StringUtils.isEmpty(vo.getUuid())){
            return AjaxResult.me().setSuccess(false).setMessage("浏览器标识不能为空!");
        }


        //判断图形验证码的正确性
        String imageKey = "CODE:IMAGE:"+vo.getUuid();
        String imageCode = redisClient.get(imageKey);
        if(!(vo.getImageCode().equals(imageCode))){
            return AjaxResult.me().setSuccess(false).setMessage("图形验证码错误!");
        }

        //判断短信验证码的正确性
        String smsKey = "CODE:SMS:"+vo.getPhoneNum();
        String smsCode = redisClient.get(smsKey);
        if(StringUtils.isEmpty(smsCode)){
            return AjaxResult.me().setSuccess(false).setMessage("短信验证码不存在!");
        }
        String code = (smsCode.split(","))[0];
        if(!(vo.getSmsCode().equals(code))){
            return AjaxResult.me().setSuccess(false).setMessage("短信验证码错误!");
        }

        //成功调用service进行注册
        try {
            ssoService.register(vo);
            return AjaxResult.me().setSuccess(true).setMessage("注册成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("注册失败!"+e.getMessage());
        }

    }
}
